package ciyuanwutuobang.threadagainstdeath;

import org.bukkit.Bukkit;
import org.bukkit.entity.Player;

import java.lang.reflect.Method;
import java.util.Calendar;
import java.util.TimerTask;

import static ciyuanwutuobang.threadagainstdeath.ThreadAgainstDeath.MSG_PREFIX;
import static ciyuanwutuobang.threadagainstdeath.ThreadAgainstDeath.logInfo;


/**
 * @author 150149
 */
public class MainThreadCheck extends TimerTask {
    private static Method tickMethod;
    private double stopTime = 0.0D;
    private long timer = Calendar.getInstance().getTimeInMillis();
    private static Boolean IsKa = false;

    public MainThreadCheck() {
        ThreadAgainstDeath.logInfo("线程防死已开启");
    }

    static {
        try {
            tickMethod = Class.forName("org.spigotmc.WatchdogThread").getDeclaredMethod("tick");
        } catch (Exception ignored) { }
    }

    public static void wttick() {
        try {
            if (tickMethod != null) {
                tickMethod.invoke(null);
            }
            if (IsKa) {
                IsKa=false;
            } else {
                for (Player player : Bukkit.getServer().getOnlinePlayers()) {
                    player.sendMessage(MSG_PREFIX +"服务器卡顿期已结束，继续游戏吧");
                }
                return;
            }

            for (Player player : Bukkit.getServer().getOnlinePlayers()) {
                player.sendMessage(MSG_PREFIX + "服务器卡顿中，请不要进行游戏");
            }
        } catch (Throwable ignored) {}
    }

    private void tick() {
        this.stopTime += 0.5D;
        if (this.stopTime >= 3.0D && Calendar.getInstance().getTimeInMillis()-timer>=3000) {
            IsKa=true;
            logInfo("已激活线程,防止线程死亡");
            wttick();
            timer=Calendar.getInstance().getTimeInMillis();
        }
    }

    @Override
    public void run() {
        if (TPSCheck.CurrentTPS ==0) {
            tick();
        } else {
            this.stopTime=0;
            IsKa=false;
        }
    }
}